package com.hurui.xiaoming.activity.me;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.BaseActivity;
import com.hurui.xiaoming.bean.Li_Personal_Result;
import com.hurui.xiaoming.bean.ModifyInfo;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.BitmapUtils;
import com.hurui.xiaoming.utils.ImageOnkitKat;
import com.hurui.xiaoming.utils.TimeUtils;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MeInfoActivity extends BaseActivity implements  PermissionListener,RationaleListener {

    private LinearLayout goto_deail_info_lv ;
    private TextView title_tv ;
    private ImageView back_iv ;
    private TextView nick_name,my_sex_tv,my_barity_tv,my_address_tv,my_recommender_tv;
    private Li_Personal_Result.DataBean data;
    private ImageView my_icon_iv;
    private final int REQUEST_CODE=12001;
    private List<String> list;
    private BottomSheetDialog mBottomSheetDialog;
    private Map<String ,Object> map;
    private String time;
    private View my_birth_ll;
    private Button commit_btn;
    private View my_nick_name_ll;
    private TextView my_nick_name;
    private View address_ll;
    private View sex_ll;
    private String sex="1";
     String mySex="男";
    private String imagePath=null;
    private TextView code_ui;
    private ClipboardManager systemService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_info);
        data = ((Li_Personal_Result.DataBean) getIntent().getSerializableExtra(PamaryKeys.DATABEAN));
        systemService = ((ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE));
        initView();
    }

    @Override
    public void initView() {
        map=new HashMap<>();
        list=new ArrayList<>();
        //new 一个BottomSheetDialog对象
        mBottomSheetDialog = new BottomSheetDialog(this);
        title_tv = (TextView) findViewById(R.id.top_title_tv);
        back_iv = (ImageView) findViewById(R.id.back_iv);
        goto_deail_info_lv = (LinearLayout) findViewById(R.id.goto_deail_info_lv);

        title_tv.setText("我的信息");
        nick_name = ((TextView) findViewById(R.id.my_nick_name_tv));
        my_sex_tv= ((TextView) findViewById(R.id.my_sex_tv));
        my_barity_tv= ((TextView) findViewById(R.id.my_birth_tv));
        my_address_tv= ((TextView) findViewById(R.id.my_address_tv));
        my_recommender_tv= ((TextView) findViewById(R.id.my_recommender_tv));
        my_icon_iv = ((ImageView) findViewById(R.id.my_icon_iv));
        my_birth_ll = findViewById(R.id.my_birth_linear);
        commit_btn = ((Button) findViewById(R.id.commit_btn));
        my_nick_name_ll = findViewById(R.id.my_nick_linear);
        my_nick_name = ((TextView) findViewById(R.id.my_nick_name_tv));
        address_ll = findViewById(R.id.address_linear);
        sex_ll = findViewById(R.id.sex_ll);
        code_ui = ((TextView) findViewById(R.id.my_code_tv));
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initData();
        initAction();
    }

    private void modifyMyNickName() {
        View view = LayoutInflater.from(this).inflate(R.layout.date_layout, null, false);

        TextView text = (TextView) view.findViewById(R.id.myOK);

        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.datePicker);
        datePicker.setDrawingCacheBackgroundColor(getResources().getColor(R.color.colorAccent));
        //初始化DatePicker组件，初始化时指定监听器
        datePicker.init(1990, 01, 01, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker arg0, int year, int month, int day) {
                // 显示当前日期、时间
//                month = month + 1;
                Calendar calendar=Calendar.getInstance();
                calendar.set(year,month,day);
                Date date=calendar.getTime();
                 time = TimeUtils.getTime(date);

            }
        });
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (time!=null){
                    my_barity_tv.setText(time);
                }else{
                    time = data.getUi_birthday();
                }

                mBottomSheetDialog.dismiss();
            }
        });

        createBottomSheetDialog(view);


    }
    /**
     * 底部滑动显示
     *
     */
    private void createBottomSheetDialog( View view) {

        //获取要添加到BottomSheetDialog中的布局view

        mBottomSheetDialog.setContentView(view);
        //显示
        mBottomSheetDialog.show();
    }
    /**
     * 初始化数据
     */
    private void initData() {
        if (data!=null) {
            //性别
            if (data.getUi_sex() != null) {
                if (data.getUi_sex().toString().equals("1")) {
                   my_sex_tv.setText("男");
                } else {
                    my_sex_tv.setText("女");
                }
            }
            //昵称
            if (data.getUi_name()!=null) {
                nick_name.setText(data.getUi_name().toString());
            }
            //出生日期
                if (data.getUi_birthday()!=null){
                    my_barity_tv.setText(data.getUi_birthday());
                }
                //地址
            if (data.getUi_address()!=null){
                my_address_tv.setText(data.getUi_address());
            }
            //推荐人
            if (data.getTjr_name()!=null){
                my_recommender_tv.setText(data.getTjr_name().toString());
            }
            //用户头像
            if (data.getUi_img()!=null){
               // Glide.with(mContext).load(data.getUi_img().trim()).into(my_icon_iv);
                Log.i("jianbaopp",data.getUi_img().trim());
                Picasso.with(mContext)
                        .load("http://"+data.getUi_img().trim())
                        .placeholder(R.mipmap.camrea)
                        .error(R.mipmap.loan)
                        .into(my_icon_iv);
            }
            if (data.getMe_ui_code()!=null){
                code_ui.setText(data.getMe_ui_code());
            }
        }
    }

    /**
     *
     */
    private void commitData(){
        map.put(PamaryKeys.UI_ID, WriteReadSharedPrefs.readUserID(mContext)+"");

        map.put("ui_name", nick_name.getText().toString());
        map.put("ui_sex",sex);
        map.put("ui_birthday", my_barity_tv.getText().toString().trim());
        map.put("ui_img", "data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) my_icon_iv.getDrawable()).getBitmap()));
        map.put("ui_address", my_address_tv.getText().toString());
        apiSevice.onHttp_modify(map).enqueue(new Callback<ModifyInfo>() {
            @Override
            public void onResponse(Call<ModifyInfo> call, Response<ModifyInfo> response) {
                String status = response.body().getStatus();
                if (status.equals("sucess")){
                    onToast("修改信息成功");
                }
                if (status.equals("ui_name")){
                    onToast("真实姓名不能为空");
                }
                if (status.equals("ui_sex")){
                    onToast("性别不能为空");
                }
                if (status.equals("ui_birthday")){
                    onToast("生日不能为空");
                }
                if (status.equals("ui_address")){
                    onToast("详细地址不能为空");
                }
            }

            @Override
            public void onFailure(Call<ModifyInfo> call, Throwable t) {
                Log.e("cc", "onFailure: "+t.getMessage() );
            }
        });
    }

    @Override
    public void initAction() {
        back_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onFinish();
            }
        });

        goto_deail_info_lv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, MyDeailInfoActivity.class);
                intent.putExtra(PamaryKeys.DATABEAN,data);
                onOpen(intent);
            }
        });
        my_icon_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestSDPermission();
            }
        });
        my_birth_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyMyNickName();
            }
        });
        commit_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commitData();
            }
        });
        my_nick_name_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyNick_address(my_nick_name);
            }
        });
        address_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifyNick_address(my_address_tv);
            }
        });
        sex_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modifySex();
            }
        });
        code_ui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               if (data.getMe_ui_code()!=null){
                   systemService.setText(code_ui.getText().toString());
                   Toast.makeText(MeInfoActivity.this,"已复制到剪切板",Toast.LENGTH_SHORT).show();

               }
            }
        });
    }

    /**
     * 修改性别
     */
    private void modifySex() {

        View view = LayoutInflater.from(this).inflate(R.layout.sex_layout, null, false);
        RadioGroup group = (RadioGroup) view.findViewById(R.id.sex_radio);
        RadioButton button1 = (RadioButton) group.findViewById(R.id.male_btn);
        RadioButton button2 = (RadioButton) group.findViewById(R.id.female_btn);
        if (data.getUi_sex()!=null){
            if (data.getUi_sex().equals("1")){
               button1.setChecked(true);
            }else
                button2.setChecked(true);
        }else
           button1.setChecked(true);


        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.male_btn:
                        sex="1";
                       mySex="男";

                        break;
                    case R.id.female_btn:
                        sex="2";
                        mySex="女";

                        break;
                    default:
                    mBottomSheetDialog.dismiss();

                }
                my_sex_tv.setText(mySex);
            }
        });
        createBottomSheetDialog(view);
    }

    /**
     * 修改昵称和地址
     */
    private void modifyNick_address(final TextView tv) {

       final View view = LayoutInflater.from(this).inflate(R.layout.update_name_address, null, false);
       final EditText myName = (EditText) view.findViewById(R.id.myHobby);
        final TextView textYES = (TextView) view.findViewById(R.id.myOK);


        textYES.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(myName.getText().toString())) {
                    tv.setText(myName.getText().toString().toString());
                    //关闭软键盘
//                    imm.hideSoftInputFromWindow(myName.getWindowToken(), 100);

                }
                mBottomSheetDialog.dismiss();

            }
        });

        createBottomSheetDialog(view);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
               showKeyboard(myName);
            }  }, 90);

    }
    /**
     * 显示软键盘
     *
     */
    public void showKeyboard(EditText editText) {
        if(editText!=null){
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) editText
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    /**
     * 展示图片
     * @param path
     */
    private void displayImage(String path){

        Glide.with(mContext).load(path).into(my_icon_iv);
        list.add(path);

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null){
            return;
        }
        if (requestCode==REQUEST_CODE){
            displayImage(ImageOnkitKat.handleImageBeforeKitKat(mContext,data));
            imagePath=ImageOnkitKat.handleImageBeforeKitKat(mContext,data);
        }
    }

    private void openImage(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,REQUEST_CODE);
    }

    /**
     *权限成功回调
     * @param requestCode
     * @param grantPermissions
     */
    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        // 权限申请成功回调。

        switch (requestCode) {
            case 1:
                openImage();
                break;

        }
    }
    /**
     * 外部写的权限
     */
    private void  requestSDPermission() {
// 先判断是否有权限。
        if (AndPermission.hasPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)&& AndPermission.hasPermission(mContext,Manifest.permission.READ_EXTERNAL_STORAGE)&&
                AndPermission.hasPermission(mContext,Manifest.permission.CAMERA)) {
            // 有权限，直接do anything.startCamera9
            openImage();

        } else {
            // 申请权限。
            onToast("没有权限");
            AndPermission.with(this)
                    .requestCode(1)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                    .rationale(this)
                    .callback(this)
                    .start();
        }
    }

    /**
     * 权限拒绝
     * @param requestCode
     * @param deniedPermissions
     */
    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
        onToast("权限拒绝");
        if (AndPermission.hasAlwaysDeniedPermission(this,deniedPermissions)){
            AndPermission.defaultSettingDialog(this,200).
                    setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .show();
        }
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
        AndPermission.rationaleDialog(mContext,rationale).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
}
